package com.ashye.bindingrecyclerviewdemo;


import android.view.View;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhangwei on 2017/6/28.
 */
public class SelectionBindingRecyclerAdapter<T> extends FooterBindingRecyclerAdapter<SelectionBindingRecyclerAdapter.ItemSelectionWrapper<T>> {

    private final List<Integer> selected = new ArrayList<>();
    private boolean singleMode = true;


    public SelectionBindingRecyclerAdapter(int lid, int bid) {
        super(lid, bid);
    }

    public void addOriginData(List<T> data) {
        List<ItemSelectionWrapper<T>> list = new ArrayList<>();
        for (T datum : data) {
            list.add(wrapperItem(datum));
        }
        super.addData(list);
    }

    public void addOriginData(T item) {
        super.addData(wrapperItem(item));
    }

    public void setOriginData(List<T> data) {
        List<ItemSelectionWrapper<T>> list = new ArrayList<>();
        for (T datum : data) {
            list.add(wrapperItem(datum));
        }
        super.setData(list);
    }

    @Override
    public void onItemClicked(View view, int position, ItemSelectionWrapper<T> item) {
        onItemSelected(view, position, item.originItem);
    }

    private void onItemSelected(View v, int position, T item) {

        if (singleMode) {
            if (!selected.isEmpty()) {
                select(selected.get(0), false);
                selected.clear();
            }

            select(position, true);
            selected.add(position);
        }else {
            if (selected.contains(position)) {
                select(position, false);
                selected.remove(position);
            }else {
                select(position, true);
                selected.add(position);
            }
        }
    }

    private void select(int position, boolean isSelected) {
        if (position >= 0 && position < getItemCount()) {
            getItemData(position).selected = isSelected;
            notifyItemChanged(position);
        }
    }


    private ItemSelectionWrapper<T> wrapperItem(T item) {
        return new ItemSelectionWrapper<T>(item);
    }

    private T unWrapperItem(ItemSelectionWrapper<T> wrapper) {
        return wrapper.originItem;
    }

    public static class ItemSelectionWrapper<T> {
        public boolean selected = false;
        public T originItem;

        public ItemSelectionWrapper(T item) {
            originItem = item;
        }
    }
}
